﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Reflection;
using ARS.Control.Custom.Entity.Fields;
using ARS.Control.Custom.Entity.Model;
using ARS.DataBase.Provider;
using ARS.PublicTool;

namespace ARS.Control.Common.EntityManage
{
    public class EntityTableInfo : EntityTableInfoBase
    {

        private EntityToSql _EntityToSql;
        /// <summary>
        /// 实体转换sql
        /// </summary>
        public EntityToSql EntityToSql
        {
            get
            {
                if (_EntityToSql == null)
                {
                    _EntityToSql = new EntityToSql(Model, this);
                }
                return _EntityToSql;
            }
        }


        private Field  InitConfig(PropertyInfo property, object propertyValue)
        {
            Field field = null;
            object[] propertyAttrs = property.GetCustomAttributes(false);
            //object propertyValue = ReflectionHelper.GetObjAttrValue(typeModel, property.Remark, model);
            if (propertyAttrs.Length > 0)
            {
                ForeignKeyConfig config = null;
                foreach (var attr in propertyAttrs)
                {
                    if (attr is Field)
                    {
                        field = attr as Field;
                    }
                    else if (attr is ForeignKeyConfig)
                    {
                        config = attr as ForeignKeyConfig;
                    }
                }

                if (field != null)
                {
                    //field = propertyAttr as Field;
                    //string db_Field_Name = field.Db_Field_Name;
                    if (string.IsNullOrEmpty(field.Db_Field_Name))
                    {
                        field.Db_Field_Name = property.Name;
                    }

                    if (propertyValue == null)
                    {
                        field.Value = field.DefaultValue;
                    }
                    else
                    {
                        field.Value = propertyValue;
                    }

                    // 加载controls控件
                    //外键
                    if (field is ForeignKeyField)
                    {
                        ForeignKeyField foreignKeyField = field as ForeignKeyField;
                        //判断是不是继续EntityModel
                        if (property.PropertyType.IsSubclassOf(typeof(Control.Custom.Entity.Model.EntityModel)))
                        {
                            string assemblyPath = ConfigurationManager.AppSettings["FieldsAssembly"];
                            ARS.Control.Custom.Entity.Model.EntityModel entityModel =
                                ARS.PublicTool.ReflectionHelper.CreateObjectCache<ARS.Control.Custom.Entity.Model.EntityModel>(assemblyPath,
                                    property.PropertyType.FullName);
                            if (entityModel != null)
                            {
                                config = entityModel.GetConfig_ForeignKeyConfig();
                            }
                        }
                        foreignKeyField.SelectDbSelectConfig = config;
                        //if (field is ChoicesDialogField)
                        //{
                        //    //ChoicesDialogField choicesDialogField = field as ChoicesDialogField;
                        //    ////判断是不是继续EntityModel
                        //    //if (property.PropertyType.IsSubclassOf(typeof(Control.Custom.Entity.Model.EntityModel)))
                        //    //{
                        //    //    string assemblyPath = ConfigurationManager.AppSettings["FieldsAssembly"];
                        //    //    ARS.Control.Custom.Entity.Model.EntityModel entityModel =
                        //    //        ARS.PublicTool.ReflectionHelper.CreateObjectCache<ARS.Control.Custom.Entity.Model.EntityModel>(assemblyPath,
                        //    //            property.PropertyType.FullName);
                        //    //    if (entityModel != null)
                        //    //    {
                        //    //        config = entityModel.GetConfig_ChoicesDialogConfig();
                        //    //    }
                        //    //}
                        //    //choicesDialogField.SelectDbSelectConfig = config;
                        //}
                        //else
                        //{

                        //}                                               
                    }

                    field.Html_Control_Name = "entity" + this.FieldList.Count.ToString();
                    field.Widget.Field = field;

                }
                else
                {
                    if (this.KeyInfo.Key == null)
                    {
                        var propertyAttr = propertyAttrs[0];
                        if (propertyAttr is KeyField)
                        {
                            this.KeyInfo.Key = property.Name;
                            this.KeyInfo.Value = Convert.ToInt32(propertyValue);
                           // continue;
                        }
                    }
                    else
                    {
                        //continue;
                    }
                    
                }
            }
            if (field == null)
            {
                field = new ShowField();
                field.Value = propertyValue;
                field.Db_Field_Name = property.Name;
                field.Widget.Field = field;
            }
            return field;
        }


        public override void ItemLoop(Type typeModel, object model)
        {
            //遍历属性
            foreach (PropertyInfo property in properties)
            {


                object propertyValue = ReflectionHelper.GetObjAttrValue(typeModel, property.Name, model);
                Field field = this.InitConfig(property, propertyValue);
                if (field != null)
                {
                    this.FieldList.Add(field);
                }
            }
        }


        protected EntityTableInfo()
        {

        }

        public EntityTableInfo(object model,int type)
        {
            this.Type = type;

            //this.FormControls = new List<ARS.Control.Custom.Entity.Forms.Form>();
            this.Create(model);
        }




        public IDbDataParameter[] GetParameters(List<ARS.Control.Custom.Entity.Fields.Field> controls)
        {
            IDbDataParameter[] parameters = null;
            if (controls != null && controls.Count > 0)
            {
                parameters = DbFactory.CreateDbParameters(controls.Count);
                this.SetParameters(controls, parameters);
            }
            return parameters;
        }

        public void SetParameters(List<ARS.Control.Custom.Entity.Fields.Field> controls,
            params IDbDataParameter[] parms)
        {
            int i = 0;
            foreach (ARS.Control.Custom.Entity.Fields.Field field in controls)
            {
                //var item = control;
                //object value = field.Value;
                parms[i].ParameterName = field.Db_Field_Name;
                parms[i].Value = field.Value;
                i++;

            }
        }

        public IDbDataParameter[] GetParameters(List<ARS.Control.Custom.Entity.Forms.Form> controls)
        {
            IDbDataParameter[] parameters = null;
            if (controls != null && controls.Count > 0)
            {
                parameters = DbFactory.CreateDbParameters(controls.Count);
                this.SetParameters(controls, parameters);
            }
            return parameters;
        }

        public void SetParameters(List<ARS.Control.Custom.Entity.Forms.Form> controls,
    params IDbDataParameter[] parms)
        {
            int i = 0;
            foreach (ARS.Control.Custom.Entity.Forms.Form control in controls)
            {
                var item = control.Field;


                object value = item.Value;
                parms[i].ParameterName = item.Db_Field_Name;
                parms[i].Value = value;
                i++;

            }
        }
        /// <summary>
        /// 获取添加的参数
        /// </summary>
        /// <returns></returns>
        public IDbDataParameter[] GetAddParameters()
        {
            return this.GetParameters(this.GetFields(EntityModel.TYPE_MODIFY));
        }
        /// <summary>
        /// 获取更新的参数
        /// </summary>
        /// <returns></returns>
        public IDbDataParameter[] GetUpdateParameters()
        {
            return this.GetParameters(this.GetFields(EntityModel.TYPE_MODIFY));
        }


        public List<ARS.Control.Custom.Entity.Fields.Field> FieldList =
            new List<ARS.Control.Custom.Entity.Fields.Field>();
        /// <summary>
        /// 获取指定类型的字段
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<ARS.Control.Custom.Entity.Fields.Field> GetFields(int type)
        {
            if (type == EntityModel.TYPE_MODIFY)
            {
                return  this.FieldList.Where(field=>field.IsAllowUpdate).ToList();
            }
            else if (type==EntityModel.TYPE_ADD)
            {
                return this.FieldList.Where(field => field.IsAllowAdd).ToList();
            }
            else if (type == EntityModel.TYPE_SEARCH)
            {
                return this.FieldList.Where(field => field.RankSearch > 0).OrderBy(field => field.RankSearch).ToList();
            }
            else if (type == EntityModel.TYPE_SHOW)
            {
                return this.FieldList.Where(field => field.IsShow).OrderBy(field => field.RankList).ToList();

            }
            return null;
        }
        /// <summary>
        /// 获取添加或编辑的字段
        /// </summary>
        /// <param name="isAdd"></param>
        /// <returns></returns>
        public List<ARS.Control.Custom.Entity.Fields.Field> GetFields(bool isAdd)
        {
            if (isAdd)
            {
                return this.FieldList.Where(field => field.IsAllowAdd && !(field is HiddenInputField)).OrderBy(field =>field.Rank).ToList();                
            }
            else
            {
                return this.FieldList.Where(field => field.IsAllowUpdate && !(field is HiddenInputField)).OrderBy(field => field.Rank).ToList();
            }
            return null;
        }

        /// <summary>
        /// 添加实体到数据
        /// </summary>
        /// <param name="listNow"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SaveAddToDb(List<ARS.Control.Custom.Entity.Fields.Field> listNow)
        {
            //if (SaveToDbEvent != null)
            //{
            //    SaveAddToDb(listNow);
            //}
            //EntityToSql toSql = new EntityToSql(model, this);

            string sql = this.EntityToSql.GetAddSqlParams(listNow);
            var b = this.GetParameters(listNow);
            if (string.IsNullOrEmpty(sql) || b == null)
            {
                return 0;
            }
            object obj = ARS.DataBase.Provider.DbFactory.DbProvider.GetSingle(sql, b);
            int newId = Convert.ToInt32(obj);
            return newId;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int SaveAddToDb()
        {
            var list = this.GetFieldsNotNull(true);
            return SaveAddToDb(list);
        }
        /// <summary>
        /// 获取非空白字段
        /// </summary>
        /// <param name="isAdd"></param>
        /// <returns></returns>
        public List<ARS.Control.Custom.Entity.Fields.Field> GetFieldsNotNull(bool isAdd)
        {
            if (isAdd)
            {
                return (from field in this.FieldList

                        where field.IsAllowAdd && (field.Value != null && field.Value.ToString() != "")
                        orderby field.Rank
                        select field).ToList();
            }
            else
            {
                return (from field in this.FieldList

                        where (field.IsAllowUpdate && !(field is ForeignKeyField)) || (field.IsAllowUpdate && field is ForeignKeyField && field.Value != null && field.Value.ToString() != "")
                        orderby field.Rank
                        select field).ToList();
            }
        }


    }
}
